<template>
  <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body :close-on-click-modal="false" class="safety-dialog">
    <!-- 巡查信息 -->
    <div class="block-container">
      <div class="block-title">巡查信息</div>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <table class="safety-table">
          <tr>
            <td class="label-cell">巡查内容</td>
            <td class="content-cell" colspan="3">
              <el-input
                type="textarea"
                v-model="form.patrolContent"
                :rows="3"
                placeholder="请输入巡查内容"
              />
            </td>
          </tr>
          <tr>
            <td class="label-cell">是否有变化</td>
            <td class="content-cell" colspan="3">
              <el-radio-group v-model="form.hasChanges">
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </td>
          </tr>
          <tr>
            <td class="label-cell">巡查结果</td>
            <td class="content-cell" colspan="3">
              <el-input
                type="textarea"
                v-model="form.patrolConclusion"
                :rows="3"
                placeholder="请输入巡查结果"
              />
            </td>
          </tr>
          <tr>
            <td class="label-cell">巡查人员</td>
            <td class="content-cell">
              <el-input
                v-model="form.patrolPerson"
                placeholder="请输入巡查人员姓名"
              />
            </td>
            <td class="label-cell">巡查日期</td>
            <td class="content-cell">
              <el-date-picker
                v-model="form.patrolDate"
                type="date"
                placeholder="选择巡查日期"
                value-format="yyyy-MM-dd"
              />
            </td>
          </tr>
          <tr>
            <td class="label-cell">相关附件资料</td>
            <td class="content-cell" colspan="3">
              <el-upload
                action="#"
                :auto-upload="false"
                :file-list="photoList"
                :before-upload="handleBeforeUpload"
                :on-change="handleUploadSuccess"
                :on-remove="handleUploadRemove"
                :on-exceed="handleUploadExceed"
                :limit="10"
                multiple
                list-type="picture-card"
                accept=".jpg,.jpeg,.png"
              >
                <i class="el-icon-plus"></i>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过5MB</div>
              </el-upload>
            </td>
          </tr>
        </table>
      </el-form>
    </div>

    <el-form ref="houseForm" :model="houseInfo" label-width="100px">
      <!-- 基本信息 -->
      <div class="block-container">
        <div class="block-title">基本信息</div>
        <div class="basic-info-container">
          <!-- 左侧表单 -->
          <div class="form-section">
            <el-form ref="houseForm" :model="houseInfo" label-width="100px">
              <!-- 基本信息表单内容 -->
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="房屋名称">
                    <el-input v-model="houseInfo.houseName" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="房屋编号">
                    <el-input v-model="houseInfo.houseCode" disabled />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="省份">
                    <el-input v-model="houseInfo.provinceName" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="城市">
                    <el-input v-model="houseInfo.cityName" disabled />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="区域">
                    <el-input v-model="houseInfo.districtName" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="街道">
                    <el-input v-model="houseInfo.streetName" disabled />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="居委">
                    <el-input v-model="houseInfo.communityName" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="详细地址">
                    <el-input v-model="houseInfo.address" disabled />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="经度">
                    <el-input v-model="houseInfo.longitude" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="纬度">
                    <el-input v-model="houseInfo.latitude" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
          <!-- 右侧地图区域 -->
          <div class="map-section">
            <a-map
              v-if="houseInfo.longitude && houseInfo.latitude"
              ref="aMap"
              :longitude="houseInfo.longitude"
              :latitude="houseInfo.latitude"
              :editable="false"
            />
          </div>
        </div>
      </div>

      <!-- 房屋照片 -->
      <div class="block-container">
        <div class="block-title">房屋照片</div>
        <div class="photo-list">
          <div class="photo-item" v-for="(photo, index) in housePhotoList" :key="index">
            <el-image 
              :src="photo.url" 
              :preview-src-list="[photo.url]"
              fit="cover"
              class="photo-image">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </div>
        </div>
      </div>

      <!-- 房屋信息 -->
      <div class="block-container">
        <div class="block-title">房屋信息</div>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="土地证号">
              <el-input v-model="houseInfo.landCertificate" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="占地面积(m²)">
              <el-input v-model="houseInfo.landArea" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="土地性质">
              <el-input v-model="houseInfo.landNatureName" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="产权性质">
              <el-input v-model="houseInfo.propertyNatureName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产权单位">
              <el-input v-model="houseInfo.propertyOwner" disabled placeholder="产权单位（人）" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产权证号">
              <el-input v-model="houseInfo.propertyCertificate" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="公房面积(m²)">
              <el-input v-model="houseInfo.publicArea" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="售后面积(m²)">
              <el-input v-model="houseInfo.afterSaleArea" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="公房户数">
              <el-input v-model="houseInfo.publicHouseCount" disabled placeholder="直管公房数" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="售后户数">
              <el-input v-model="houseInfo.afterSaleCount" disabled placeholder="售后房户数" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="其他户数">
              <el-input v-model="houseInfo.otherTypeCount" disabled placeholder="其他类型户数" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="主用人数">
              <el-input v-model="houseInfo.mainUserCount" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="房屋用途">
              <el-input v-model="houseInfo.houseUsageName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="房屋类型">
              <el-input v-model="houseInfo.houseTypeName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="基础类型">
              <el-input v-model="houseInfo.foundationTypeName" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="检查等级">
              <el-input v-model="houseInfo.inspectionLevelName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="鉴定等级">
              <el-input v-model="houseInfo.appraisalLevelName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="抗震等级">
              <el-input v-model="houseInfo.seismicLevelName" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="减震情况">
              <el-input v-model="houseInfo.shockAbsorptionName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="保护类型">
              <el-input v-model="houseInfo.protectedTypeName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电梯情况">
              <el-input v-model="houseInfo.hasElevatorName" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="消防设施">
              <el-input v-model="houseInfo.hasFireProtectionName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="改造方式">
              <el-input v-model="houseInfo.isReformedName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="物业管理">
              <el-input v-model="houseInfo.hasPropertyName" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="houseInfo.isReformed === '1'">
          <el-col :span="12">
            <el-form-item label="改造单位">
              <el-input v-model="houseInfo.reformDesignUnit" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="改造时间">
              <el-input v-model="houseInfo.reformTime" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="houseInfo.isReformed === '1'">
          <el-col :span="24">
            <el-form-item label="改造内容">
              <el-input type="textarea" v-model="houseInfo.reformContent" disabled :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注说明">
              <el-input type="textarea" v-model="houseInfo.remark" disabled :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getPatrol, addPatrol, updatePatrol } from "@/api/house/patrol";
import { getHouse } from "@/api/house/house";
import { listHousePhoto, getPhotoUrl, uploadPhoto, deletePhoto } from "@/api/house/housePhoto";
import { listProvinceOptions } from "@/api/house/province";
import { listCityOptions } from "@/api/house/city";
import { listDistrictOptions } from "@/api/house/district";
import { listStreetOptions } from "@/api/house/street";
import { listCommitteeOptions } from "@/api/house/committee";
import AMap from '@/components/AMap'
import { getToken } from "@/utils/auth";

export default {
  name: "PatrolForm",
  components: {
    AMap
  },
  dicts: [
    'house_risk_level',
    'house_structure_type',
    'house_land_nature',
    'house_property_nature',
    'house_usage_type',
    'house_type',
    'house_foundation_type', 
    'house_inspection_level',
    'house_appraisal_level',
    'house_seismic_level',
    'house_shock_absorption',
    'house_protected_type'
  ],
  data() {
    return {
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 房屋信息
      houseInfo: {
        houseName: '',
        houseCode: '',
        address: '',
        provinceName: '',
        cityName: '',
        districtName: '',
        streetName: '',
        communityName: '',
        longitude: null,
        latitude: null,
        buildingArea: '',
        buildDate: '',
        riskLevelName: '',
        structureTypeName: '',
        totalHouseholds: '',
        landCertificate: '',
        landArea: '',
        landNatureName: '',
        propertyNatureName: '',
        propertyOwner: '',
        propertyCertificate: '',
        publicArea: '',
        afterSaleArea: '',
        publicHouseCount: '',
        afterSaleCount: '',
        otherTypeCount: '',
        mainUserCount: '',
        houseUsageName: '',
        houseTypeName: '',
        foundationTypeName: '',
        inspectionLevelName: '',
        appraisalLevelName: '',
        seismicLevelName: '',
        shockAbsorptionName: '',
        protectedTypeName: '',
        hasElevatorName: '',
        hasFireProtectionName: '',
        isReformedName: '',
        hasPropertyName: '',
        reformDesignUnit: '',
        reformTime: '',
        reformContent: '',
        remark: '',
        isReformed: '0'
      },
      // 房屋照片列表
      housePhotoList: [],
      // 上传相关数据
      uploadUrl: process.env.VUE_APP_BASE_API + "/house/photo/upload",
      headers: {
        Authorization: "Bearer " + getToken()
      },
      uploadData: {
        source: 'patrol'
      },
      canEdit: true,
      // 添加巡查表单数据
      form: {
        id: null,
        houseId: null,
        houseName: null,
        patrolContent: '',
        hasChanges: '否',
        patrolConclusion: '',
        patrolPerson: '',
        patrolDate: null,
        remark: ''
      },
      // 表单校验
      rules: {
        houseId: [
          { required: true, message: "房屋ID不能为空", trigger: "blur" }
        ],
        patrolDate: [
          { required: true, message: "巡查日期不能为空", trigger: "blur" }
        ],
        patrolContent: [
          { required: true, message: "巡查内容不能为空", trigger: "blur" }
        ],
        patrolPerson: [
          { required: true, message: "巡查人员不能为空", trigger: "blur" }
        ]
      },
      // 巡查照片列表
      photoList: [],
      // 待删除的照片ID列表
      deletedPhotoIds: []
    };
  },
  methods: {
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.houseInfo = {
        houseName: '',
        houseCode: '',
        address: '',
        provinceName: '',
        cityName: '',
        districtName: '',
        streetName: '',
        communityName: '',
        longitude: null,
        latitude: null,
        buildingArea: '',
        buildDate: '',
        riskLevelName: '',
        structureTypeName: '',
        totalHouseholds: '',
        landCertificate: '',
        landArea: '',
        landNatureName: '',
        propertyNatureName: '',
        propertyOwner: '',
        propertyCertificate: '',
        publicArea: '',
        afterSaleArea: '',
        publicHouseCount: '',
        afterSaleCount: '',
        otherTypeCount: '',
        mainUserCount: '',
        houseUsageName: '',
        houseTypeName: '',
        foundationTypeName: '',
        inspectionLevelName: '',
        appraisalLevelName: '',
        seismicLevelName: '',
        shockAbsorptionName: '',
        protectedTypeName: '',
        hasElevatorName: '',
        hasFireProtectionName: '',
        isReformedName: '',
        hasPropertyName: '',
        reformDesignUnit: '',
        reformTime: '',
        reformContent: '',
        remark: '',
        isReformed: '0'
      };
      // 清空照片列表
      this.housePhotoList = [];
      this.photoList = [];
      this.deletedPhotoIds = [];
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.open = true;
      this.title = "添加巡查记录";
      if (row) {
        this.form.houseId = row.houseId;
        // 获取房屋照片列表
        this.getPhotoList(row.houseId, 'house', null);
        // 获取房屋详细信息
        getHouse(row.houseId).then(async response => {
          const houseData = response.data;
          // 设置房屋名称
          this.form.houseName = houseData.houseName;
          // 按顺序加载省市区街道数据
          if (houseData.province) {
            await this.loadProvinceOptions();
          }
          if (houseData.city) {
            await this.loadCityOptions(houseData.province);
          }
          if (houseData.district) {
            await this.loadDistrictOptions(houseData.city);
          }
          if (houseData.street) {
            await this.loadStreetOptions(houseData.district);
          }
          if (houseData.community) {
            await this.loadCommitteeOptions(houseData.street);
          }

          this.houseInfo = {
            ...this.houseInfo,
            houseName: houseData.houseName,
            houseCode: houseData.houseCode,
            address: houseData.address,
            provinceName: this.getRegionName('province', houseData.province),
            cityName: this.getRegionName('city', houseData.city),
            districtName: this.getRegionName('district', houseData.district),
            streetName: this.getRegionName('street', houseData.street),
            communityName: this.getRegionName('community', houseData.community),
            longitude: houseData.longitude,
            latitude: houseData.latitude,
            buildingArea: houseData.buildingArea,
            buildDate: houseData.buildDate,
            riskLevelName: this.getDictLabel('house_risk_level', houseData.riskLevel),
            structureTypeName: this.getDictLabel('house_structure_type', houseData.structureType),
            totalHouseholds: houseData.totalHouseholds,
            landCertificate: houseData.landCertificate,
            landArea: houseData.landArea,
            landNatureName: this.getDictLabel('house_land_nature', houseData.landNature),
            propertyNatureName: this.getDictLabel('house_property_nature', houseData.propertyNature),
            propertyOwner: houseData.propertyOwner,
            propertyCertificate: houseData.propertyCertificate,
            publicArea: houseData.publicArea,
            afterSaleArea: houseData.afterSaleArea,
            publicHouseCount: houseData.publicHouseCount,
            afterSaleCount: houseData.afterSaleCount,
            otherTypeCount: houseData.otherTypeCount,
            mainUserCount: houseData.mainUserCount,
            houseUsageName: this.getDictLabel('house_usage_type', houseData.houseUsage),
            houseTypeName: this.getDictLabel('house_type', houseData.houseType),
            foundationTypeName: this.getDictLabel('house_foundation_type', houseData.foundationType),
            inspectionLevelName: this.getDictLabel('house_inspection_level', houseData.inspectionLevel),
            appraisalLevelName: this.getDictLabel('house_appraisal_level', houseData.appraisalLevel),
            seismicLevelName: this.getDictLabel('house_seismic_level', houseData.seismicLevel),
            shockAbsorptionName: this.getDictLabel('house_shock_absorption', houseData.shockAbsorption),
            protectedTypeName: this.getDictLabel('house_protected_type', houseData.protectedType),
            hasElevatorName: houseData.hasElevator === '1' ? '有' : '无',
            hasFireProtectionName: houseData.hasFireProtection === '1' ? '有' : '无',
            isReformedName: houseData.isReformed === '1' ? '已改造' : '未改造',
            hasPropertyName: houseData.hasProperty === '1' ? '有' : '无',
            reformDesignUnit: houseData.reformDesignUnit,
            reformTime: houseData.reformTime,
            reformContent: houseData.reformContent,
            remark: houseData.remark,
            isReformed: houseData.isReformed
          };
        });
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getPatrol(id).then(response => {
        this.form = response.data;
        // 获取房屋照片列表
        this.getPhotoList(this.form.houseId, 'house', null);
        // 获取巡查照片列表
        this.getPhotoList(this.form.houseId, 'patrol', this.form.id);
        // 获取房屋详细信息
        getHouse(this.form.houseId).then(async response => {
          const houseData = response.data;
          // 按顺序加载省市区街道数据
          if (houseData.province) {
            await this.loadProvinceOptions();
          }
          if (houseData.city) {
            await this.loadCityOptions(houseData.province);
          }
          if (houseData.district) {
            await this.loadDistrictOptions(houseData.city);
          }
          if (houseData.street) {
            await this.loadStreetOptions(houseData.district);
          }
          if (houseData.community) {
            await this.loadCommitteeOptions(houseData.street);
          }

          this.houseInfo = {
            ...this.houseInfo,
            houseName: houseData.houseName,
            houseCode: houseData.houseCode,
            address: houseData.address,
            provinceName: this.getRegionName('province', houseData.province),
            cityName: this.getRegionName('city', houseData.city),
            districtName: this.getRegionName('district', houseData.district),
            streetName: this.getRegionName('street', houseData.street),
            communityName: this.getRegionName('community', houseData.community),
            longitude: houseData.longitude,
            latitude: houseData.latitude,
            buildingArea: houseData.buildingArea,
            buildDate: houseData.buildDate,
            riskLevelName: this.getDictLabel('house_risk_level', houseData.riskLevel),
            structureTypeName: this.getDictLabel('house_structure_type', houseData.structureType),
            totalHouseholds: houseData.totalHouseholds,
            landCertificate: houseData.landCertificate,
            landArea: houseData.landArea,
            landNatureName: this.getDictLabel('house_land_nature', houseData.landNature),
            propertyNatureName: this.getDictLabel('house_property_nature', houseData.propertyNature),
            propertyOwner: houseData.propertyOwner,
            propertyCertificate: houseData.propertyCertificate,
            publicArea: houseData.publicArea,
            afterSaleArea: houseData.afterSaleArea,
            publicHouseCount: houseData.publicHouseCount,
            afterSaleCount: houseData.afterSaleCount,
            otherTypeCount: houseData.otherTypeCount,
            mainUserCount: houseData.mainUserCount,
            houseUsageName: this.getDictLabel('house_usage_type', houseData.houseUsage),
            houseTypeName: this.getDictLabel('house_type', houseData.houseType),
            foundationTypeName: this.getDictLabel('house_foundation_type', houseData.foundationType),
            inspectionLevelName: this.getDictLabel('house_inspection_level', houseData.inspectionLevel),
            appraisalLevelName: this.getDictLabel('house_appraisal_level', houseData.appraisalLevel),
            seismicLevelName: this.getDictLabel('house_seismic_level', houseData.seismicLevel),
            shockAbsorptionName: this.getDictLabel('house_shock_absorption', houseData.shockAbsorption),
            protectedTypeName: this.getDictLabel('house_protected_type', houseData.protectedType),
            hasElevatorName: houseData.hasElevator === '1' ? '有' : '无',
            hasFireProtectionName: houseData.hasFireProtection === '1' ? '有' : '无',
            isReformedName: houseData.isReformed === '1' ? '已改造' : '未改造',
            hasPropertyName: houseData.hasProperty === '1' ? '有' : '无',
            reformDesignUnit: houseData.reformDesignUnit,
            reformTime: houseData.reformTime,
            reformContent: houseData.reformContent,
            remark: houseData.remark,
            isReformed: houseData.isReformed
          };
        });
        this.open = true;
        this.title = "修改巡查记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const formData = new FormData();
          
          // 将表单数据转换为JSON字符串，并添加到patrol参数中
          const patrolData = {
            id: this.form.id,
            houseId: this.form.houseId,
            houseName: this.form.houseName,
            patrolContent: this.form.patrolContent,
            hasChanges: this.form.hasChanges,
            patrolConclusion: this.form.patrolConclusion,
            patrolPerson: this.form.patrolPerson,
            patrolDate: this.form.patrolDate,
            remark: this.form.remark
          };

          // 添加调试信息
          console.log('提交的 patrolData:', patrolData);

          formData.append('patrol', new Blob([JSON.stringify(patrolData)], {
            type: 'application/json'
          }));
          
          // 添加新上传的照片
          const newPhotos = this.photoList.filter(p => p.raw);
          newPhotos.forEach(photo => {
            formData.append('photos', photo.raw);
          });
          
          if (this.form.id) {
            // 编辑模式 - 添加要删除的照片ID
            const deletedPhotoIds = this.deletedPhotoIds || [];
            deletedPhotoIds.forEach(id => {
              formData.append('deletedPhotoIds', id);
            });
            
            updatePatrol(formData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.$emit("ok"); // 通知父组件刷新列表
            });
          } else {
            // 新增模式
            addPatrol(formData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.$emit("ok"); // 通知父组件刷新列表
            });
          }
        }
      });
    },
    /** 获取字典标签 */
    getDictLabel(dictType, value) {
      if (!dictType || !value) return '';
      const dict = this.dict.type[dictType];
      if (!dict) return '';
      const item = dict.find(d => d.value === value);
      return item ? item.label : '';
    },
    /** 获取照片列表 */
    getPhotoList(houseId, source, sourceId) {
      if (!houseId) return;
      listHousePhoto({ houseId: houseId, source: source, sourceId: sourceId }).then(response => {
        const photoList = response.data || [];
        // 获取每张照片的URL
        const promises = photoList.map(photo => 
          getPhotoUrl(photo.photoId).then(res => ({
            ...photo,
            url: res.data,
            name: photo.originalName
          }))
        );
        Promise.all(promises).then(photos => {
          if (source === 'house') {
            // 房屋照片
            this.housePhotoList = photos;
          } else if (source === 'patrol') {
            // 巡查照片
            this.photoList = photos;
          }
        });
      });
    },
    /** 获取地区名称 */
    getRegionName(type, value) {
      const options = {
        province: this.provinceOptions,
        city: this.cityOptions,
        district: this.districtOptions,
        street: this.streetOptions,
        community: this.committeeOptions
      }[type];
      
      if (value && options) {
        const found = options.find(item => item.value === value);
        return found ? found.label : '';
      }
      return '';
    },
    /** 加载省份数据 */
    loadProvinceOptions() {
      return listProvinceOptions().then(response => {
        this.provinceOptions = response.rows.map(item => ({
          value: item.provinceCode,
          label: item.provinceName
        }));
      });
    },
    /** 加载城市数据 */
    loadCityOptions(provinceCode) {
      return listCityOptions({ provinceCode: provinceCode }).then(response => {
        this.cityOptions = response.rows.map(item => ({
          value: item.cityCode,
          label: item.cityName
        }));
      });
    },
    /** 加载区域数据 */
    loadDistrictOptions(cityCode) {
      return listDistrictOptions({ cityCode: cityCode }).then(response => {
        this.districtOptions = response.rows.map(item => ({
          value: item.districtCode,
          label: item.districtName
        }));
      });
    },
    /** 加载街道数据 */
    loadStreetOptions(districtCode) {
      return listStreetOptions({ districtCode: districtCode }).then(response => {
        this.streetOptions = response.rows.map(item => ({
          value: item.streetCode,
          label: item.streetName
        }));
      });
    },
    /** 加载居委数据 */
    loadCommitteeOptions(streetCode) {
      if (!streetCode) {
        this.committeeOptions = [];
        return Promise.resolve();
      }
      return listCommitteeOptions({ streetCode: streetCode, pageSize: 100 }).then(response => {
        this.committeeOptions = response.rows.map(item => ({
          value: String(item.committeeCode),
          label: item.committeeName
        }));
      });
    },
    /** 文件上传之前的钩子 */
    handleBeforeUpload(file) {
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isImage) {
        this.$message.error('只能上传JPG/PNG格式的图片！');
        return false;
      }
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.$message.error('图片大小不能超过 5MB!');
        return false;
      }
      return true;
    },
    /** 文件上传成功的钩子 */
    handleUploadSuccess(file) {
      try {
        if (file && file.raw) {
          const fileObj = {
            name: file.name,
            raw: file.raw,
            status: 'ready'
          };

          try {
            fileObj.url = URL.createObjectURL(file.raw);
          } catch (e) {
            console.warn('创建预览URL失败:', e);
            fileObj.url = '';
          }

          this.photoList.push(fileObj);
          console.log('添加照片:', fileObj);
        } else {
          console.warn('文件对象无效:', file);
        }
      } catch (error) {
        console.error('处理上传文件时出错:', error);
      }
    },
    /** 文件超出个数限制的钩子 */
    handleUploadExceed() {
      this.$message.warning(`最多只能上传10张图片`);
    },
    /** 删除文件的钩子 */
    handleUploadRemove(file) {
      const index = this.photoList.findIndex(item => item.name === file.name);
      if (index !== -1) {
        const photo = this.photoList[index];
        // 如果是已有的图片（有photoId），记录到待删除列表
        if (photo.photoId) {
          this.deletedPhotoIds.push(photo.photoId);
        }
        // 如果存在预览URL，释放它
        if (photo.url) {
          try {
            URL.revokeObjectURL(photo.url);
          } catch (e) {
            console.warn('释放预览URL失败:', e);
          }
        }
        this.photoList.splice(index, 1);
      }
    },
    /** 标签页切换事件 */
    handleTabClick(tab) {
      this.activeTab = tab.name;
    }
  }
};
</script>

<style lang="scss" scoped>
.safety-dialog {
  ::v-deep .el-dialog__body {
    padding: 20px;
    max-height: 80vh;
    overflow-y: auto;
  }

  ::v-deep .el-dialog {
    margin-top: 5vh !important;
  }

  ::v-deep .el-dialog__header {
    padding: 15px 20px;
    border-bottom: 1px solid #f0f0f0;
  }

  ::v-deep .el-dialog__footer {
    padding: 15px 20px;
    border-top: 1px solid #f0f0f0;
  }
}

/* 基本信息区域布局 */
.basic-info-container {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.form-section {
  flex: 1;
  min-width: 0; /* 防止flex子项溢出 */
}

.map-section {
  flex: 1;
  min-height: 400px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.safety-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
  font-size: 14px;
  border: 1px solid #d9d9d9;
  color: #333;

  td {
    padding: 12px 15px;
    border: 1px solid #d9d9d9;
    vertical-align: top;
    line-height: 1.8;
  }

  .label-cell {
    background-color: #fafafa;
    font-weight: 500;
    width: 120px;
    text-align: right;
    vertical-align: middle;
  }

  .content-cell {
    min-height: 40px;
    
    .el-input,
    .el-textarea {
      width: 100%;
    }

    .el-date-editor {
      width: 100%;
    }

    .el-radio-group {
      display: flex;
      align-items: center;
      height: 100%;
    }

    .el-radio {
      margin-right: 30px;
      line-height: 32px;
    }
  }
}

.group-title {
  font-weight: 500;
  margin-bottom: 8px;
  color: #333;
}

.checkbox-line {
  margin-bottom: 8px;
  line-height: 1.8;
}

.option-desc {
  color: #666;
  font-size: 13px;
  margin: 4px 0;
}

.el-checkbox-group {
  display: block;
  margin: 8px 0;

  .el-checkbox {
    display: inline-block;
    margin-right: 20px;
    margin-bottom: 8px;
    white-space: normal;
    line-height: 1.5;
  }
}

.el-radio-group {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;

  .el-radio {
    display: inline-flex;
    align-items: center;
    margin-right: 20px;
    margin-bottom: 0;
    white-space: nowrap;
  }
}

.el-textarea {
  width: 100%;
  
  ::v-deep .el-textarea__inner {
    border-radius: 2px;
    border-color: #d9d9d9;
    padding: 8px 12px;
  }
}

.el-date-editor {
  width: 180px;
}

.dialog-footer {
  .el-button {
    padding: 9px 20px;
  }
}

// 必选项样式
::v-deep .el-form-item.is-required .el-form-item__label:before {
  color: #f56c6c;
}

// 表单项间距
.el-form-item {
  margin-bottom: 18px;
}

.block-container {
  margin-bottom: 20px;

  .block-title {
    font-size: 15px;
    font-weight: bold;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
  }
}

.el-input.is-disabled .el-input__inner {
  color: #333;
}

.photo-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  padding: 10px 0;
}

.photo-item {
  width: 160px;
  height: 160px;
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid #e4e7ed;
  position: relative;
  
  &:hover {
    border-color: #409EFF;
    .photo-actions {
      display: flex;
    }
  }
}

.photo-actions {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.6);
  padding: 5px;
  display: none;
  justify-content: center;
  align-items: center;

  .el-button {
    color: #fff;
    &:hover {
      color: #409EFF;
    }
  }
}

.photo-upload {
  width: 160px;
  height: 160px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  
  &:hover {
    border-color: #409EFF;
  }

  .el-icon-plus {
    font-size: 28px;
    color: #8c939d;
    margin-bottom: 8px;
  }

  .upload-text {
    font-size: 12px;
    color: #606266;
  }
}

.photo-image {
  width: 100%;
  height: 100%;
  display: block;
}

::v-deep .el-image {
  width: 100%;
  height: 100%;

  .el-image__inner {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: #f5f7fa;
    color: #909399;
    font-size: 30px;
  }
}

.el-upload--picture-card {
  width: 148px;
  height: 148px;
  line-height: 148px;
}

.el-upload-list--picture-card .el-upload-list__item {
  width: 148px;
  height: 148px;
}

.el-upload-list--picture-card .el-upload-list__item-thumbnail {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style> 